package com.rj.util;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

public class ForEachUtils {
    /**
     * 遍历集合并拼接字符
     * @param collection 集合对象
     * @param manConsumer 对象处理函数
     * @param builder 比较器
     * @param separator 分割符
     * @param <T>
     */
    public static  <T> void exec(Collection<T> collection, BiConsumer<T,StringBuilder> manConsumer, StringBuilder builder, String separator){
        exec(collection,manConsumer,builder,separator,null, 0);
    }
    /**
     * 遍历集合并拼接字符
     * @param map 集合对象
     * @param manConsumer 对象处理函数
     * @param builder 比较器
     * @param separator 分割符
     */
    public static  void exec(Map map, BiConsumer<Map.Entry,StringBuilder> manConsumer, StringBuilder builder, String separator){
        exec(map,manConsumer,builder,separator,null, 0);
    }
    /**
     * 遍历集合并拼接字符
     * @param collection 集合对象
     * @param manConsumer 对象处理函数
     * @param builder 比较器
     * @param separator 分割符
     * @param <T>
     */
    public static  <T> void exec(Collection<T> collection, BiConsumer<T,StringBuilder> manConsumer, StringBuilder builder, String separator, Consumer<StringBuilder> batchConsumer,int batchSize){
        boolean first = true;
        boolean batchFlag = batchConsumer!=null;
        AtomicInteger atomicInteger=null;
        if(batchFlag){
            atomicInteger=new AtomicInteger(0);
        }
        for (T e:collection) {
            if(!first){
                builder.append(separator);
            }
            first=false;
            manConsumer.accept(e, builder);
            if(batchFlag && atomicInteger.incrementAndGet() > batchSize){
                batchConsumer.accept(builder);
                builder.setLength(0);
                atomicInteger.set(0);
                first=true;
            }
        }
        if(batchFlag && atomicInteger.get() > 0){
            batchConsumer.accept(builder);
            builder.setLength(0);
            atomicInteger.set(0);
        }
    }
    /**
     * 遍历集合并拼接字符
     * @param map 集合对象
     * @param manConsumer 对象处理函数
     * @param builder 比较器
     * @param separator 分割符
     */
    public static  void exec(Map map, BiConsumer<Map.Entry,StringBuilder> manConsumer, StringBuilder builder, String separator, Consumer<StringBuilder> batchConsumer,int batchSize){
         exec(map.entrySet(), manConsumer, builder, separator, batchConsumer, batchSize);
    }

}
